// [REFACTORED] 文件名和函数名稍作调整以更清晰
// 并且将所有函数设为公共函数，因为它们在包内部多处被使用

class WeekData {
  final DateTime start;
  final DateTime end;
  final bool isThisWeek;
  final int weekOfYear;

  WeekData({
    required this.start,
    required this.end,
    required this.isThisWeek,
    required this.weekOfYear,
  });
}



/// 格式化日期为 YYYY.MM.DD
String formatDate(DateTime date) {
  String year = date.year.toString();
  String month = date.month.toString().padLeft(2, '0');
  String day = date.day.toString().padLeft(2, '0');
  return "$year.$month.$day";
}

/// 计算给定日期是当年的第几周
int getWeekOfYear(DateTime date) {
  DateTime firstDayOfYear = DateTime(date.year, 1, 1);
  int dayOfYear = date.difference(firstDayOfYear).inDays + 1;
  return ((dayOfYear - 1) / 7).floor() + 1;
}

///  生成一个周数据列表，不再包含UI字符串
List<WeekData> generateWeekDataList(
    DateTime initialDate, int yearsBack, bool showLaterTime) {
  int currentYear = initialDate.year;
  int startYear = currentYear - yearsBack;
  List<WeekData> weeksList = [];

  DateTime loopStartDate = DateTime(startYear, 1, 1);
  DateTime loopEndDate =
  showLaterTime ? DateTime(currentYear + 1, 12, 31) : DateTime.now();

  int daysToMonday = (loopStartDate.weekday - DateTime.monday + 7) % 7;
  DateTime currentWeekStart = loopStartDate.subtract(Duration(days: daysToMonday));

  while (currentWeekStart.isBefore(loopEndDate)) {
    DateTime currentWeekEnd = currentWeekStart.add(const Duration(days: 6));

    if (!showLaterTime && currentWeekEnd.isAfter(DateTime.now())) {
      if (currentWeekStart.isBefore(DateTime.now())) {
        // 本周，包含今天，允许加入
      } else {
        break; // 整周都在未来，跳出
      }
    }

    final now = DateTime.now();
    final bool isThisWeek = (currentWeekStart.isBefore(now) ||
        currentWeekStart.isAtSameMomentAs(now)) &&
        (currentWeekEnd.isAfter(now) ||
            currentWeekEnd.isAtSameMomentAs(now));

    weeksList.add(WeekData(
      start: currentWeekStart,
      end: currentWeekEnd,
      isThisWeek: isThisWeek,
      weekOfYear: getWeekOfYear(currentWeekStart),
    ));

    if (!showLaterTime && currentWeekEnd.isAfter(DateTime.now())) {
      break;
    }

    currentWeekStart = currentWeekStart.add(const Duration(days: 7));
  }
  return weeksList;
}

/// 从周列表的字符串中解析出开始和结束的DateTime对象
Map<String, DateTime> parseWeekValue(String weekValue) {
  String week = weekValue.split('(')[0];
  String startDateStr = week.split('~')[0];
  String endDateStr = week.split('~')[1];
  List<String> startParts = startDateStr.split('.');
  List<String> endParts = endDateStr.split('.');
  DateTime currentWeekStart = DateTime(
    int.parse(startParts[0]),
    int.parse(startParts[1]),
    int.parse(startParts[2]),
  );
  DateTime currentWeekEnd = DateTime(
    int.parse(endParts[0]),
    int.parse(endParts[1]),
    int.parse(endParts[2]),
  );
  return {"startTime": currentWeekStart, "endTime": currentWeekEnd};
}
